<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;

/**
 * 报工管理
 *
 * @icon fa fa-clipboard
 */
class Report extends Backend
{
    /**
     * Report模型对象
     * @var \app\admin\model\scanwork\Report
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Report;
        $this->view->assign("statusList", $this->model->getStatusList());
        
        // 设置表格配置
        $this->assignconfig('table', [
            'columns' => [
                'id' => ['title' => 'ID', 'width' => '80px'],
                'allocation.order.order_no' => ['title' => '订单号', 'width' => '150px'],
                'allocation.model.product.name' => ['title' => '产品名称', 'width' => '120px'],
                'allocation.model.name' => ['title' => '型号', 'width' => '100px'],
                'allocation.process.name' => ['title' => '工序', 'width' => '100px'],
                'user.nickname' => ['title' => '员工', 'width' => '100px'],
                'quantity' => ['title' => '数量', 'width' => '80px'],
                'wage' => ['title' => '工资', 'width' => '100px'],
                'status' => ['title' => '状态', 'width' => '100px', 'formatter' => 'status'],
                'createtime' => ['title' => '报工时间', 'width' => '150px', 'formatter' => 'datetime'],
                'operate' => ['title' => '操作', 'width' => '200px', 'formatter' => 'operate']
            ],
            'operate' => [
                'audit' => [
                    'title' => '审核',
                    'icon' => 'fa fa-check',
                    'class' => 'btn btn-xs btn-success',
                    'url' => 'audit_page',
                    'params' => ['ids' => '{ids}']
                ],
                'reject' => [
                    'title' => '拒绝',
                    'icon' => 'fa fa-times',
                    'class' => 'btn btn-xs btn-danger',
                    'url' => 'audit_page',
                    'params' => ['ids' => '{ids}', 'status' => '2']
                ],
                'view' => [
                    'title' => '详情',
                    'icon' => 'fa fa-eye',
                    'class' => 'btn btn-xs btn-info',
                    'url' => 'view'
                ],
                'edit' => [
                    'title' => '编辑',
                    'icon' => 'fa fa-pencil',
                    'class' => 'btn btn-xs btn-primary',
                    'url' => 'edit'
                ],
                'del' => [
                    'title' => '删除',
                    'icon' => 'fa fa-trash',
                    'class' => 'btn btn-xs btn-danger',
                    'url' => 'del'
                ]
            ]
        ]);
    }

    /**
     * 报工管理列表，with 关联 allocation（含 order、model.product、process）和 user
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with([
                    'allocation' => function($query) {
                        $query->with(['order', 'model.product', 'process']);
                    },
                    'user'
                ])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 新增报工
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $allocation = \app\admin\model\scanwork\Allocation::get($params['allocation_id']);
            if (!$allocation) {
                $this->error('分配不存在');
            }
            
            $processPrice = \app\admin\model\scanwork\ProcessPrice::where([
                'model_id' => $allocation->model_id,
                'process_id' => $allocation->process_id
            ])->find();
            if (!$processPrice) {
                $this->error('工序工资未设置');
            }
            
            $workType = isset($params['work_type']) ? $params['work_type'] : 'piece';
            $itemNos = isset($params['item_nos']) ? $params['item_nos'] : [];
            
            if ($workType == 'piece') {
                $quantity = count($itemNos);
                $wage = $quantity * $processPrice->piece_price;
                $data = [
                    'allocation_id' => $allocation->id,
                    'user_id' => $allocation->user_id,
                    'quantity' => $quantity,
                    'item_nos' => json_encode($itemNos),
                    'wage' => $wage,
                    'remark' => isset($params['remark']) ? $params['remark'] : '',
                    'createtime' => time()
                ];
            } else {
                $work_hours = $params['work_hours'];
                $wage = $work_hours * $processPrice->time_price;
                $data = [
                    'allocation_id' => $allocation->id,
                    'user_id' => $allocation->user_id,
                    'work_hours' => $work_hours,
                    'wage' => $wage,
                    'remark' => isset($params['remark']) ? $params['remark'] : '',
                    'createtime' => time()
                ];
            }
            
            Db::startTrans();
            try {
                $report = \app\admin\model\scanwork\Report::create($data);
                
                // 更新产品编号状态
                if ($workType == 'piece' && !empty($itemNos)) {
                    \app\admin\model\scanwork\ProductItem::updateItemsStatus($itemNos, 1, $report->id);
                }
                
                Db::commit();
                $this->success('报工成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('报工失败：' . $e->getMessage());
            }
        }
        
        // 获取可报工的产品编号
        $allocationId = $this->request->get('allocation_id');
        if ($allocationId) {
            $items = \app\admin\model\scanwork\ProductItem::where([
                'allocation_id' => $allocationId,
                'status' => 0
            ])->select();
            $this->view->assign('items', $items);
        }
        
        return $this->view->fetch();
    }

    /**
     * 日报工页面
     */
    public function dailyReport()
    {
        return $this->view->fetch();
    }

    /**
     * 审核页面
     */
    public function audit_page()
    {
        $ids = $this->request->get('ids');
        $status = $this->request->get('status', '1'); // 默认通过
        $dialog = $this->request->get('dialog', 0); // 是否为弹窗模式
        
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $idsArr = is_array($ids) ? $ids : explode(',', $ids);
        $reports = $this->model
            ->with([
                'allocation' => function($query) {
                    $query->with(['order', 'model.product', 'process']);
                },
                'user'
            ])
            ->where('id', 'in', $idsArr)
            ->select();
        
        $this->view->assign('reports', $reports);
        $this->view->assign('ids', $ids);
        $this->view->assign('status', $status);
        $this->view->assign('dialog', $dialog);
        
        // 如果是弹窗模式，使用简化的布局
        if ($dialog) {
            return $this->view->fetch('audit_dialog');
        }
        
        return $this->view->fetch('audit');
    }

    /**
     * 审核报工（通过/拒绝）
     */
    public function audit()
    {
        $ids = $this->request->post('ids');
        $status = $this->request->post('status');
        $reason = $this->request->post('audit_reason', '');
        $itemAuditData = $this->request->post('item_audit_data', []); // 产品编号审核数据
        $qualityStatus = $this->request->post('quality_status', 1); // 质量状态
        $auditImages = $this->request->post('audit_images', []); // 审核图片
        $auditVideos = $this->request->post('audit_videos', []); // 审核视频
        $auditNotes = $this->request->post('audit_notes', ''); // 审核备注
        
        // 调试信息
        error_log("审核调试 - POST数据: " . json_encode($_POST));
        error_log("审核调试 - FILES数据: " . json_encode($_FILES));
        
        if (!$ids || !in_array($status, ['1', '2'])) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        $idsArr = is_array($ids) ? $ids : explode(',', $ids);
        $success = 0;
        $fail = 0;
        
        foreach ($idsArr as $id) {
            $report = $this->model->get($id);
            if (!$report) {
                $fail++;
                continue;
            }
            
            try {
                if ($status == '1') {
                    // 审核通过，调用confirm方法重新计算工资
                    $report->confirm();
                    
                    // 更新审核信息
                    $report->save([
                        'audit_time' => time(),
                        'audit_user_id' => $this->auth->id,
                        'audit_notes' => $auditNotes,
                        'quality_status' => $qualityStatus
                    ]);
                } else {
                    // 审核拒绝，调用reject方法
                    $report->reject($reason);
                    
                    // 更新审核信息
                    $report->save([
                        'audit_time' => time(),
                        'audit_user_id' => $this->auth->id,
                        'audit_notes' => $auditNotes,
                        'quality_status' => $qualityStatus
                    ]);
                }
                
                // 处理产品编号审核
                if (!empty($itemAuditData) && isset($itemAuditData[$id])) {
                    $this->processItemAudit($id, $itemAuditData[$id], $status);
                }
                
                // 处理产品编号审核文件上传
                $this->processItemAuditFiles($id, $status);
                
                // 处理审核视频上传
                $this->processAuditVideos($id, $status);
                
                // 处理审核图片上传
                $this->processAuditImages($id, $status);
                
                // 保存审核图片和视频
                if (!empty($auditImages)) {
                    $this->saveAuditImages($id, $auditImages);
                }
                
                if (!empty($auditVideos)) {
                    $this->saveAuditVideos($id, $auditVideos);
                }
                
                // 审核通过后创建溯源码
                if ($status == '1') {
                    $this->createTraceCodeAfterAudit($report);
                }
                
                $success++;
            } catch (\Exception $e) {
                $fail++;
                error_log("审核失败 - 报工ID: {$id}, 错误: " . $e->getMessage());
            }
        }
        
        if ($success > 0) {
            return json(['code' => 1, 'msg' => "审核成功：{$success} 条，失败：{$fail} 条"]);
        } else {
            return json(['code' => 0, 'msg' => '审核失败']);
        }
    }

    /**
     * 处理产品编号审核
     */
    private function processItemAudit($reportId, $itemData, $status)
    {
        foreach ($itemData as $itemNo => $auditInfo) {
            $item = \app\admin\model\scanwork\ProductItem::where('item_no', $itemNo)->find();
            if ($item) {
                // 更新产品编号状态
                $item->status = 2; // 已审核
                $item->audit_user_id = $this->auth->id;
                $item->audit_time = time();
                $item->save();
                
                // 保存审核图片
                if (isset($auditInfo['images']) && !empty($auditInfo['images'])) {
                    foreach ($auditInfo['images'] as $imageUrl) {
                        \app\admin\model\scanwork\ItemAuditImage::create([
                            'item_id' => $item->id,
                            'report_id' => $reportId,
                            'image_url' => $imageUrl,
                            'upload_user_id' => $this->auth->id,
                            'audit_status' => $status,
                            'audit_reason' => isset($auditInfo['reason']) ? $auditInfo['reason'] : '',
                            'createtime' => time()
                        ]);
                    }
                }
            }
        }
    }

    /**
     * 处理产品编号审核文件上传
     */
    private function processItemAuditFiles($reportId, $status)
    {
        $adminId = $this->auth->id;
        
        error_log("processItemAuditFiles - 开始处理，reportId: {$reportId}, status: {$status}");
        error_log("processItemAuditFiles - FILES结构: " . print_r($_FILES, true));
        
        // 检查是否有文件需要上传
        if (empty($_FILES['item_audit_files']) || !is_array($_FILES['item_audit_files']['name'])) {
            error_log("processItemAuditFiles - 没有文件需要上传，跳过处理");
            return;
        }
        
        // 使用云存储服务
        try {
            $cloudService = new \app\common\service\ScanworkCloudService();
        } catch (\Exception $e) {
            error_log("processItemAuditFiles - 云存储服务初始化失败: " . $e->getMessage());
            return;
        }
        
        // 按照前端报工的方式处理文件上传
        if (!empty($_FILES['item_audit_files']) && is_array($_FILES['item_audit_files']['name'])) {
            foreach ($_FILES['item_audit_files']['name'] as $reportIdKey => $itemFiles) {
                if ($reportIdKey == $reportId && is_array($itemFiles)) {
                    foreach ($itemFiles as $itemNo => $files) {
                        $item = \app\admin\model\scanwork\ProductItem::where('item_no', $itemNo)->find();
                        if (!$item) continue;
                        
                        $count = 0;
                        if (is_array($files)) {
                            foreach ($files as $k => $filename) {
                                if (!isset($_FILES['item_audit_files']['error'][$reportIdKey][$itemNo][$k]) || 
                                    $_FILES['item_audit_files']['error'][$reportIdKey][$itemNo][$k] != 0) {
                                    continue;
                                }
                                
                                if ($count >= 9) break;
                                
                                // 构建文件数组
                                $file = [
                                    'name' => $_FILES['item_audit_files']['name'][$reportIdKey][$itemNo][$k],
                                    'type' => $_FILES['item_audit_files']['type'][$reportIdKey][$itemNo][$k],
                                    'tmp_name' => $_FILES['item_audit_files']['tmp_name'][$reportIdKey][$itemNo][$k],
                                    'error' => $_FILES['item_audit_files']['error'][$reportIdKey][$itemNo][$k],
                                    'size' => $_FILES['item_audit_files']['size'][$reportIdKey][$itemNo][$k]
                                ];
                                
                                // 上传到云存储
                                $result = $cloudService->uploadAuditImage($file);
                                
                                if ($result['success']) {
                                    // 保存到产品审核图片表
                                    \app\admin\model\scanwork\ItemAuditImage::create([
                                        'item_id' => $item->id,
                                        'report_id' => $reportId,
                                        'image_url' => $result['url'],
                                        'cloud_file_id' => $result['file_id'],
                                        'upload_user_id' => $adminId,
                                        'audit_status' => $status,
                                        'audit_reason' => '',
                                        'createtime' => time()
                                    ]);
                                    $count++;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 处理审核图片上传
     */
    private function processAuditImages($reportId, $status)
    {
        $adminId = $this->auth->id;
        
        error_log("processAuditImages - 开始处理，reportId: {$reportId}, status: {$status}");
        error_log("processAuditImages - FILES结构: " . print_r($_FILES, true));
        
        // 检查是否有文件需要上传
        if (empty($_FILES['audit_images']) || !is_array($_FILES['audit_images']['name'])) {
            error_log("processAuditImages - 没有文件需要上传，跳过处理");
            return;
        }
        
        // 使用云存储服务
        try {
            $cloudService = new \app\common\service\ScanworkCloudService();
        } catch (\Exception $e) {
            error_log("processAuditImages - 云存储服务初始化失败: " . $e->getMessage());
            return;
        }
        
        // 处理审核图片上传
        if (!empty($_FILES['audit_images']) && is_array($_FILES['audit_images']['name'])) {
            foreach ($_FILES['audit_images']['name'] as $reportIdKey => $files) {
                if ($reportIdKey == $reportId && is_array($files)) {
                    $data = [];
                    foreach ($files as $k => $filename) {
                        if (!isset($_FILES['audit_images']['error'][$reportIdKey][$k]) || 
                            $_FILES['audit_images']['error'][$reportIdKey][$k] != 0) {
                            continue;
                        }
                        
                        $file = [
                            'name' => $_FILES['audit_images']['name'][$reportIdKey][$k],
                            'type' => $_FILES['audit_images']['type'][$reportIdKey][$k],
                            'tmp_name' => $_FILES['audit_images']['tmp_name'][$reportIdKey][$k],
                            'error' => $_FILES['audit_images']['error'][$reportIdKey][$k],
                            'size' => $_FILES['audit_images']['size'][$reportIdKey][$k]
                        ];
                        
                        $result = $cloudService->uploadAuditImage($file);
                        if ($result['success']) {
                            $data[] = [
                                'report_id' => $reportId,
                                'image_url' => $result['url'],
                                'upload_user_id' => $adminId,
                                'createtime' => time()
                            ];
                        }
                    }
                    
                    if (!empty($data)) {
                        \think\Db::name('scanwork_audit_image')->insertAll($data);
                    }
                }
            }
        }
    }

    /**
     * 保存审核图片
     */
    private function saveAuditImages($reportId, $images)
    {
        $adminId = $this->auth->id;
        $data = [];
        
        foreach ($images as $image) {
            $data[] = [
                'report_id' => $reportId,
                'image_url' => $image,
                'upload_user_id' => $adminId,
                'createtime' => time()
            ];
        }
        
        if (!empty($data)) {
            \think\Db::name('scanwork_audit_image')->insertAll($data);
        }
    }

    /**
     * 保存审核视频
     */
    private function saveAuditVideos($reportId, $videos)
    {
        $adminId = $this->auth->id;
        $data = [];
        
        foreach ($videos as $video) {
            $data[] = [
                'report_id' => $reportId,
                'video_url' => $video,
                'upload_user_id' => $adminId,
                'createtime' => time()
            ];
        }
        
        if (!empty($data)) {
            \think\Db::name('scanwork_audit_video')->insertAll($data);
        }
    }

    /**
     * 审核通过后创建溯源码
     */
    private function createTraceCodeAfterAudit($report)
    {
        try {
            // 检查是否已经创建过溯源码
            $existingTrace = \app\admin\model\scanwork\TraceCode::getTraceByReportId($report->id);
            if ($existingTrace) {
                return; // 已存在，直接返回
            }
            
            // 获取报工相关信息
            $allocation = $report->allocation;
            if (!$allocation) {
                return;
            }
            
            // 获取产品、工序、员工等信息
            $productName = $allocation->model && $allocation->model->product ? $allocation->model->product->name : '';
            $processName = $allocation->process ? $allocation->process->name : '';
            $workerName = $report->user ? $report->user->nickname : '';
            $auditorName = $this->auth->nickname ?? '';
            
            // 获取产品编号（如果有的话）
            $itemNo = '';
            $productItem = \app\admin\model\scanwork\ProductItem::where('report_id', $report->id)->find();
            if ($productItem) {
                $itemNo = $productItem->item_no;
            }
            
            // 创建溯源码记录
            $traceData = [
                'product_name' => $productName,
                'item_no' => $itemNo,
                'process_name' => $processName,
                'worker_name' => $workerName,
                'auditor_name' => $auditorName,
                'remark' => '审核通过',
                'audit_time' => time()
            ];
            
            $traceCode = \app\admin\model\scanwork\TraceCode::createTraceCode($report->id, $traceData);
            
            if ($traceCode) {
                // 生成溯源码二维码图片
                \app\admin\model\scanwork\TraceCode::generateQrCodeImage($traceCode->trace_code);
            }
            
        } catch (\Exception $e) {
            // 静默处理异常，不影响审核流程
        }
    }
    
    /**
     * 处理审核视频上传
     */
    private function processAuditVideos($reportId, $status)
    {
        $adminId = $this->auth->id;
        
        error_log("processAuditVideos - 开始处理，reportId: {$reportId}, status: {$status}");
        error_log("processAuditVideos - FILES结构: " . print_r($_FILES, true));
        
        // 检查是否有文件需要上传
        if ((empty($_FILES['audit_videos']) || !is_array($_FILES['audit_videos']['name'])) && 
            (empty($_FILES['item_audit_videos']) || !is_array($_FILES['item_audit_videos']['name']))) {
            error_log("processAuditVideos - 没有文件需要上传，跳过处理");
            return;
        }
        
        // 使用云存储服务
        try {
            $cloudService = new \app\common\service\ScanworkCloudService();
        } catch (\Exception $e) {
            error_log("processAuditVideos - 云存储服务初始化失败: " . $e->getMessage());
            return;
        }
        
        // 处理普通报工审核视频
        error_log("processAuditVideos - 检查audit_videos: " . (isset($_FILES['audit_videos']) ? '存在' : '不存在'));
        if (!empty($_FILES['audit_videos']) && is_array($_FILES['audit_videos']['name'])) {
            error_log("processAuditVideos - audit_videos文件数量: " . count($_FILES['audit_videos']['name']));
            foreach ($_FILES['audit_videos']['name'] as $k => $filename) {
                error_log("processAuditVideos - 处理文件: {$filename}, 错误码: " . $_FILES['audit_videos']['error'][$k]);
                if (!isset($_FILES['audit_videos']['error'][$k]) || 
                    $_FILES['audit_videos']['error'][$k] != 0) {
                    error_log("processAuditVideos - 跳过文件: {$filename}, 错误码: " . $_FILES['audit_videos']['error'][$k]);
                    continue;
                }
                
                // 构建文件数组
                $file = [
                    'name' => $_FILES['audit_videos']['name'][$k],
                    'type' => $_FILES['audit_videos']['type'][$k],
                    'tmp_name' => $_FILES['audit_videos']['tmp_name'][$k],
                    'error' => $_FILES['audit_videos']['error'][$k],
                    'size' => $_FILES['audit_videos']['size'][$k]
                ];
                
                error_log("processAuditVideos - 普通审核视频文件信息: " . print_r($file, true));
                
                // 检查文件类型
                $allowedExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', '3gp', 'webm'];
                $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                
                if (!in_array($fileExtension, $allowedExtensions)) {
                    error_log("processAuditVideos - 不支持的文件类型: {$fileExtension}");
                    continue;
                }
                
                // 先保存到本地
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = date('Y-m-d') . '/' . uniqid() . '_' . time() . '.' . $ext;
                
                $localDir = ROOT_PATH . 'public/uploads/audit_video/' . date('Y-m-d');
                if (!is_dir($localDir)) {
                    mkdir($localDir, 0755, true);
                }
                $localPath = $localDir . '/' . basename($filename);
                
                if (move_uploaded_file($file['tmp_name'], $localPath)) {
                    // 设置文件权限
                    chmod($localPath, 0755);
                    $localUrl = '/uploads/audit_video/' . $filename;
                    
                    error_log("processAuditVideos - 本地保存成功: {$localPath}");
                    
                    // 构建新的文件数组，使用本地保存的文件
                    $localFile = [
                        'name' => $file['name'],
                        'type' => $file['type'],
                        'tmp_name' => $localPath,
                        'error' => 0,
                        'size' => $file['size']
                    ];
                    
                    // 使用云存储服务上传
                    $result = $cloudService->uploadAuditVideo($localFile);
                    
                    if ($result['success']) {
                        // 保存到审核视频表
                        \think\Db::name('scanwork_audit_video')->insert([
                            'report_id' => $reportId,
                            'video_url' => $result['url'],
                            'cloud_file_id' => $result['file_id'],
                            'upload_user_id' => $adminId,
                            'audit_status' => $status,
                            'audit_reason' => '',
                            'createtime' => time()
                        ]);
                        
                        error_log("processAuditVideos - 普通审核视频上传成功: {$result['url']}");
                    } else {
                        error_log("processAuditVideos - 普通审核视频上传失败: " . $result['message']);
                    }
                } else {
                    error_log("processAuditVideos - 本地保存失败: {$localPath}");
                }
            }
        }
        
        // 处理产品编号审核视频
        error_log("processAuditVideos - 检查item_audit_videos: " . (isset($_FILES['item_audit_videos']) ? '存在' : '不存在'));
        if (!empty($_FILES['item_audit_videos']) && is_array($_FILES['item_audit_videos']['name'])) {
            error_log("processAuditVideos - item_audit_videos结构: " . print_r($_FILES['item_audit_videos'], true));
            foreach ($_FILES['item_audit_videos']['name'] as $reportIdKey => $itemVideos) {
                error_log("processAuditVideos - 处理reportIdKey: {$reportIdKey}, 当前reportId: {$reportId}");
                if ($reportIdKey == $reportId && is_array($itemVideos)) {
                    foreach ($itemVideos as $itemNo => $videos) {
                        error_log("processAuditVideos - 处理itemNo: {$itemNo}");
                        $item = \app\admin\model\scanwork\ProductItem::where('item_no', $itemNo)->find();
                        if (!$item) {
                            error_log("processAuditVideos - 未找到产品编号: {$itemNo}");
                            continue;
                        }
                        
                        $count = 0;
                        if (is_array($videos)) {
                            error_log("processAuditVideos - 处理videos数组，数量: " . count($videos));
                            foreach ($videos as $k => $filename) {
                                error_log("processAuditVideos - 处理文件 {$k}: {$filename}");
                                if (!isset($_FILES['item_audit_videos']['error'][$reportIdKey][$itemNo][$k]) || 
                                    $_FILES['item_audit_videos']['error'][$reportIdKey][$itemNo][$k] != 0) {
                                    error_log("processAuditVideos - 文件 {$k} 上传错误: " . $_FILES['item_audit_videos']['error'][$reportIdKey][$itemNo][$k]);
                                    continue;
                                }
                                
                                if ($count >= 9) break;
                                
                                // 构建文件数组
                                $file = [
                                    'name' => $_FILES['item_audit_videos']['name'][$reportIdKey][$itemNo][$k],
                                    'type' => $_FILES['item_audit_videos']['type'][$reportIdKey][$itemNo][$k],
                                    'tmp_name' => $_FILES['item_audit_videos']['tmp_name'][$reportIdKey][$itemNo][$k],
                                    'error' => $_FILES['item_audit_videos']['error'][$reportIdKey][$itemNo][$k],
                                    'size' => $_FILES['item_audit_videos']['size'][$reportIdKey][$itemNo][$k]
                                ];
                                
                                error_log("processAuditVideos - 产品编号审核视频文件信息: " . print_r($file, true));
                                
                                // 检查文件类型
                                $allowedExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', '3gp', 'webm'];
                                $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                                
                                error_log("processAuditVideos - 文件扩展名: {$fileExtension}");
                                
                                if (!in_array($fileExtension, $allowedExtensions)) {
                                    error_log("processAuditVideos - 不支持的文件类型: {$fileExtension}");
                                    continue;
                                }
                                
                                // 先保存到本地
                                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                                $filename = date('Y-m-d') . '/' . uniqid() . '_' . time() . '.' . $ext;
                                
                                $localDir = ROOT_PATH . 'public/uploads/audit_video/' . date('Y-m-d');
                                if (!is_dir($localDir)) {
                                    mkdir($localDir, 0755, true);
                                }
                                $localPath = $localDir . '/' . basename($filename);
                                
                                if (move_uploaded_file($file['tmp_name'], $localPath)) {
                                    // 设置文件权限
                                    chmod($localPath, 0755);
                                    $localUrl = '/uploads/audit_video/' . $filename;
                                    
                                    error_log("processAuditVideos - 本地保存成功: {$localPath}");
                                    
                                    // 构建新的文件数组，使用本地保存的文件
                                    $localFile = [
                                        'name' => $file['name'],
                                        'type' => $file['type'],
                                        'tmp_name' => $localPath,
                                        'error' => 0,
                                        'size' => $file['size']
                                    ];
                                    
                                    // 使用云存储服务上传
                                    $result = $cloudService->uploadAuditVideo($localFile);
                                    
                                    if ($result['success']) {
                                        // 保存到产品编号审核图片表（视频也存储在这里）
                                        \think\Db::name('scanwork_item_audit_image')->insert([
                                            'item_id' => $item->id,
                                            'report_id' => $reportId,
                                            'image_url' => $result['url'],
                                            'cloud_file_id' => $result['file_id'],
                                            'upload_user_id' => $adminId,
                                            'audit_status' => $status,
                                            'audit_reason' => '',
                                            'createtime' => time()
                                        ]);
                                        
                                        error_log("processAuditVideos - 产品编号审核视频上传成功: {$result['url']}");
                                        $count++;
                                    } else {
                                        error_log("processAuditVideos - 产品编号审核视频上传失败: " . $result['message']);
                                    }
                                } else {
                                    error_log("processAuditVideos - 本地保存失败: {$localPath}");
                                }
                            }
                        }
                    }
                }
            }
        }
        
        error_log("processAuditVideos - 处理完成");
    }

    /**
     * 上传审核图片
     */
    public function uploadAuditImage()
    {
        try {
            // 检查是否有文件上传
            if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                return json(['code' => 0, 'msg' => '请选择文件']);
            }
            
            // 使用云存储服务上传
            $cloudService = new \app\common\service\ScanworkCloudService();
            $result = $cloudService->uploadAuditImage($_FILES['file']);
            
            if ($result['success']) {
                return json([
                    'code' => 1, 
                    'msg' => '上传成功', 
                    'url' => $result['url'],
                    'file_id' => $result['file_id']
                ]);
            } else {
                return json(['code' => 0, 'msg' => $result['message']]);
            }
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => '上传失败：' . $e->getMessage()]);
        }
    }

    /**
     * 上传审核视频
     */
    public function uploadAuditVideo()
    {
        try {
            // 检查是否有文件上传
            if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                return json(['code' => 0, 'msg' => '请选择文件']);
            }
            
            $file = $_FILES['file'];
            
            // 检查文件类型
            $allowedExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', '3gp', 'webm'];
            $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            
            if (!in_array($fileExtension, $allowedExtensions)) {
                return json(['code' => 0, 'msg' => '不支持的视频格式，请上传MP4、AVI、MOV、WMV、FLV、3GP或WEBM格式的视频']);
            }
            
            // 检查文件大小（限制为100MB）
            if ($file['size'] > 100 * 1024 * 1024) {
                return json(['code' => 0, 'msg' => '视频文件过大，请上传小于100MB的视频']);
            }
            
            // 先保存到本地
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = date('Y-m-d') . '/' . uniqid() . '_' . time() . '.' . $ext;
            
            $localDir = ROOT_PATH . 'public/uploads/audit_video/' . date('Y-m-d');
            if (!is_dir($localDir)) {
                mkdir($localDir, 0755, true);
            }
            $localPath = $localDir . '/' . basename($filename);
            
            if (move_uploaded_file($file['tmp_name'], $localPath)) {
                // 设置文件权限
                chmod($localPath, 0755);
                $localUrl = '/uploads/audit_video/' . $filename;
                
                // 使用云存储服务上传
                $cloudService = new \app\common\service\ScanworkCloudService();
                
                // 构建新的文件数组，使用本地保存的文件
                $localFile = [
                    'name' => $file['name'],
                    'type' => $file['type'],
                    'tmp_name' => $localPath,
                    'error' => 0,
                    'size' => $file['size']
                ];
                
                $result = $cloudService->uploadAuditVideo($localFile);
                
                if ($result['success']) {
                    return json([
                        'code' => 1, 
                        'msg' => '上传成功', 
                        'url' => $result['url'],
                        'local_url' => $localUrl,
                        'file_id' => $result['file_id'],
                        'upload_status' => 'success',
                        'qiniu_status' => 'uploaded'
                    ]);
                } else {
                    return json(['code' => 0, 'msg' => '视频上传失败：' . $result['message']]);
                }
            } else {
                return json(['code' => 0, 'msg' => '本地保存失败']);
            }
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => '上传失败：' . $e->getMessage()]);
        }
    }

    /**
     * 上传到七牛云（复制自Scanwork.php）
     */
    private function uploadToQiniuSimple($filePath, $filename)
    {
        try {
            // 从数据库获取七牛云配置
            $qiniuConfig = \think\Db::name('config')->where('name', 'qiniu')->find();
            if (!$qiniuConfig) {
                return ['success' => false, 'message' => '七牛云配置不存在'];
            }
            
            $config = json_decode($qiniuConfig['value'], true);
            if (!$config || !isset($config['access_key']) || !isset($config['secret_key']) || !isset($config['bucket']) || !isset($config['domain'])) {
                return ['success' => false, 'message' => '七牛云配置不完整'];
            }
            
            // 生成上传token
            $policy = [
                'scope' => $config['bucket'],
                'deadline' => time() + 3600,
                'returnBody' => json_encode(['key' => '$(key)', 'hash' => '$(etag)', 'size' => '$(fsize)', 'mimeType' => '$(mimeType)'])
            ];
            
            $policyEncoded = base64_encode(json_encode($policy));
            $sign = hash_hmac('sha1', $policyEncoded, $config['secret_key'], true);
            $token = $config['access_key'] . ':' . base64_encode($sign) . ':' . $policyEncoded;
            
            // 准备上传数据
            $postData = [
                'token' => $token,
                'key' => $filename,
                'file' => new \CURLFile($filePath)
            ];
            
            // 上传到七牛云
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://up-z2.qiniup.com/');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode == 200) {
                $result = json_decode($response, true);
                if ($result && isset($result['key'])) {
                    $cloudUrl = rtrim($config['domain'], '/') . '/' . $result['key'];
                    return [
                        'success' => true,
                        'url' => $cloudUrl,
                        'file_id' => $result['key']
                    ];
                }
            }
            
            return ['success' => false, 'message' => '七牛云上传失败：' . $response];
        } catch (Exception $e) {
            return ['success' => false, 'message' => '七牛云上传异常：' . $e->getMessage()];
        }
    }

    /**
     * 获取报工日报数据（日期+员工+报工数+总工资）
     */
    public function getDailyReport()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        $reports = $this->model
            ->with(['user'])
            ->where('status', 1)
            ->where('createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')])
            ->field('user_id, FROM_UNIXTIME(createtime, "%Y-%m-%d") as date, SUM(quantity) as quantity, SUM(wage) as wage')
            ->group('date,user_id')
            ->order('date asc')
            ->select();
        $data = [];
        foreach ($reports as $report) {
            $data[] = [
                'date' => $report['date'],
                'user' => $report->user ? $report->user->nickname : '',
                'quantity' => $report['quantity'],
                'wage' => $report['wage']
            ];
        }
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 查看报工详情，展示图片
     */
    public function view($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('报工记录不存在');
        }
        
        // 获取普通报工图片（计时工作）
        $images = \think\Db::name('scanwork_report_image')->where('report_id', $row->id)->select();
        
        // 获取产品编号报工图片（计件工作）
        $itemImages = \think\Db::name('scanwork_item_report_image')
            ->alias('iri')
            ->join('scanwork_product_item pi', 'iri.item_id = pi.id')
            ->join('user u', 'iri.upload_user_id = u.id')
            ->where('iri.report_id', $row->id)
            ->field('iri.*, pi.item_no, u.nickname as upload_user_name')
            ->select();
        
        // 获取审核图片
        $auditImages = \think\Db::name('scanwork_audit_image')
            ->alias('ai')
            ->join('fa_user u', 'u.id = ai.upload_user_id')
            ->where('ai.report_id', $row->id)
            ->field('ai.*, u.nickname as upload_user_name')
            ->select();
        
        // 获取产品编号审核图片（排除.mp4文件）
        $itemAuditImages = \think\Db::name('scanwork_item_audit_image')
            ->alias('iai')
            ->join('scanwork_product_item pi', 'iai.item_id = pi.id')
            ->join('user u', 'iai.upload_user_id = u.id')
            ->where('iai.report_id', $row->id)
            ->where('iai.image_url', 'not like', '%.mp4')
            ->field('iai.*, pi.item_no, u.nickname as upload_user_name')
            ->select();
        
        // 获取审核视频
        $auditVideos = \think\Db::name('scanwork_audit_video')
            ->alias('av')
            ->join('fa_user u', 'u.id = av.upload_user_id')
            ->where('av.report_id', $row->id)
            ->field('av.*, u.nickname as upload_user_name')
            ->select();
        
        // 获取产品编号审核视频（从scanwork_item_audit_image表中筛选.mp4文件）
        $itemAuditVideos = \think\Db::name('scanwork_item_audit_image')
            ->alias('iai')
            ->join('scanwork_product_item pi', 'iai.item_id = pi.id')
            ->join('user u', 'iai.upload_user_id = u.id')
            ->where('iai.report_id', $row->id)
            ->where('iai.image_url', 'like', '%.mp4')
            ->field('iai.*, pi.item_no, u.nickname as upload_user_name')
            ->select();
        
        // 为视频数据添加video_url字段
        foreach ($itemAuditVideos as &$video) {
            $video['video_url'] = $video['image_url'];
            $video['thumb_url'] = ''; // 暂时为空
        }
        
        $this->view->assign('images', $images);
        $this->view->assign('itemImages', $itemImages);
        $this->view->assign('auditImages', $auditImages);
        $this->view->assign('itemAuditImages', $itemAuditImages);
        $this->view->assign('auditVideos', $auditVideos);
        $this->view->assign('itemAuditVideos', $itemAuditVideos);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 删除报工图片（后台）
     */
    public function delete_image($id)
    {
        $img = \think\Db::name('scanwork_report_image')->find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        
        try {
            // 如果有云存储文件ID，删除云存储文件
            if (!empty($img['cloud_file_id'])) {
                $cloudService = new \app\common\service\ScanworkCloudService();
                $cloudService->deleteFile($img['cloud_file_id']);
            } else {
                // 删除本地文件
                @unlink(ROOT_PATH . 'public' . $img['image_url']);
            }
            
            \think\Db::name('scanwork_report_image')->delete($id);
            $this->success('图片已删除');
        } catch (Exception $e) {
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 删除产品编号报工图片（后台）
     */
    public function delete_item_image($id)
    {
        $img = \think\Db::name('scanwork_item_report_image')->find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        
        try {
            // 如果有云存储文件ID，删除云存储文件
            if (!empty($img['cloud_file_id'])) {
                $cloudService = new \app\common\service\ScanworkCloudService();
                $cloudService->deleteFile($img['cloud_file_id']);
            } else {
                // 删除本地文件
                @unlink(ROOT_PATH . 'public' . $img['image_url']);
            }
            
            \think\Db::name('scanwork_item_report_image')->delete($id);
            $this->success('产品编号报工图片已删除');
        } catch (Exception $e) {
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 删除产品编号审核图片（后台）
     */
    public function delete_item_audit_image($id)
    {
        $img = \think\Db::name('scanwork_item_audit_image')->find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        
        try {
            // 如果有云存储文件ID，删除云存储文件
            if (!empty($img['cloud_file_id'])) {
                $cloudService = new \app\common\service\ScanworkCloudService();
                $cloudService->deleteFile($img['cloud_file_id']);
            } else {
                // 删除本地文件
                @unlink(ROOT_PATH . 'public' . $img['image_url']);
            }
            
            \think\Db::name('scanwork_item_audit_image')->delete($id);
            $this->success('产品编号审核图片已删除');
        } catch (Exception $e) {
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 删除审核图片（后台）
     */
    public function delete_audit_image($id)
    {
        $img = \think\Db::name('scanwork_audit_image')->find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        
        try {
            // 如果有云存储文件ID，删除云存储文件
            if (!empty($img['cloud_file_id'])) {
                $cloudService = new \app\common\service\ScanworkCloudService();
                $cloudService->deleteFile($img['cloud_file_id']);
            } else {
                // 删除本地文件
                @unlink(ROOT_PATH . 'public' . $img['image_url']);
            }
            
            \think\Db::name('scanwork_audit_image')->delete($id);
            $this->success('审核图片已删除');
        } catch (Exception $e) {
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 主动报工管理
     */
    public function activeReport()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 查询主动报工记录
            $list = \think\Db::name('scanwork_active_report')
                ->alias('ar')
                ->join('scanwork_order o', 'ar.order_id = o.id')
                ->join('scanwork_model m', 'ar.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'ar.process_id = pr.id')
                ->join('user u', 'ar.user_id = u.id')
                ->field('ar.*, o.order_no, o.customer_name, p.name as product_name, m.name as model_name, pr.name as process_name, u.nickname as user_name')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
                
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核主动报工
     */
    public function auditActiveReport()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status'); // 1=通过，2=拒绝
        $audit_reason = $this->request->post('audit_reason', '');
        
        if (!$id) {
            $this->error('参数错误');
        }
        
        $activeReport = \think\Db::name('scanwork_active_report')->where('id', $id)->find();
        if (!$activeReport) {
            $this->error('主动报工记录不存在');
        }
        
        \think\Db::startTrans();
        try {
            // 直接更新主动报工记录状态
            \think\Db::name('scanwork_active_report')->where('id', $id)->update([
                'status' => $status,
                'audit_reason' => $audit_reason,
                'audit_user_id' => $this->auth->id,
                'audit_time' => time()
            ]);
            
            \think\Db::commit();
            $this->success('审核成功');
        } catch (\Exception $e) {
            \think\Db::rollback();
            $this->error('审核失败：' . $e->getMessage());
        }
    }
}
